package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {


    @Autowired
    private MinioClient minioClient ;

    @Autowired
    private MinioProperties minioProperties ;

    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //1.判断桶是否存在
        boolean bucketExistFlag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        //2.不存在，则创建新桶,并设置策略
        if(!bucketExistFlag){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            String configStr = String.format("""
                    {
                      "Statement" : [ {
                        "Action" : "s3:GetObject",
                        "Effect" : "Allow",
                        "Principal" : "*",
                        "Resource" : "arn:aws:s3:::%s/*"
                      } ],
                      "Version" : "2012-10-17"
                    }
                    """ , minioProperties.getBucketName()) ;
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(configStr).build());
        }
        //3.拼接文件名称并进行文件上传
        //文件名 : 年月日/UUID-文件名
        String nowStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String uuidStr = UUID.randomUUID().toString() ;
        String fileName = nowStr+"/"+uuidStr+"-"+file.getOriginalFilename();
            // 文件名这样可以避免重复
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())        //桶名称，配置文件中的
                .object(fileName)
                .stream(file.getInputStream(),file.getSize(),-1)
                .build());

        //     http://192.168.9.100:9001        /            lease                            /

        return minioProperties.getEndpoint()+ File.separatorChar+minioProperties.getBucketName()+File.separatorChar+fileName;
    }
}

